import React, { useEffect, useState, useCallback, useRef } from 'react';
import './indexRoom.less';
import { Button, Card, Col, Form, Input, Row, Select, Switch, message, notification } from 'antd';
import svgImage from '../../images/TRoom.png';
import Hoter from '../../images/Hoter.png';
import { ProForm, ProFormSelect } from '@ant-design/pro-components';
import useWebSocket from '@/hooks/UseWebsocket';
import {
  ChangeRoomType,
  CheckRoomcard,
  CheckoutUserRoom,
  GetAdminCard,
  GetAllRoomList,
  GetSetcardTimer,
  IssuingCheckin,
  NoCardcheckout,
  TeamCheckin,
  UsercheckinList,
  getBuildingsList,
  getLogLossCardCardNum,
  getRoomTypeList,
  lostRoomCard,
} from './service';
import dayjs from 'dayjs';
import {
  increment,
  changeCardname,
  changeRoomChinkList,
  changeTrueList,
  changeChinkListFlag,
  changeBULostCard,
  setGetNowCardMsg,
  setChangeRoomList,
} from './counter/counterSlice';
import { useDispatch, useSelector } from 'react-redux';
import { FlagSwitch, RoomStatus, isPastflag, useArrsort } from './RoomFunc';
import { IsManage, useDetermineCardType } from '@/hooks/DetermineCardType';
import { useDeleteConfirm } from '@/hooks/useAlartMolder';
import { InfoCircleOutlined } from '@ant-design/icons';
import lodash from 'lodash';
import ModalComponent from './modal';
import UserMsgModel from './UserMsgModel';
import ShowDrawerForm from './components/showDrawerForm';
import Addoccupants from './components/Addoccupants';
import ChinkHistoryModal from './components/ChinkHistoryModal';
import BatchCardReturns from './components/BatchCardReturns';
import { getLocale, useIntl } from '@umijs/max';
import { CleanCard, Read_Card, SetupCard, Write_LossCard } from '@/utils/Send';
import H5Model from './components/H5Model';

const UserGroupList = React.memo(() => {
  const currentLocale = getLocale();
  const intl = useIntl();
  // 按楼层渲染的列表
  const [list, setList] = useState<RoomList[]>([]);
  // 不安楼层渲染的列表
  const [list2, setlist2] = useState<RoomList[]>([]);
  // 打开子组件的状态
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  // 传入子组件的房间信息
  const [selectedItem, setSelectedItem] = useState<getAllRoom | null>(null);
  // 是否按楼层显示
  const [isFloorVisible, setIsFloorVisible] = useState<boolean>(true);
  // 渲染房型
  const [RoomType, setRoomType] = useState<RoomType[]>([]);
  // 读卡之后的弹窗
  const [useflag, setuseflag] = useState(false);
  // 房型ID
  const [typeid, settypeid] = useState<number[]>([]);
  // 读卡弹窗的卡类型
  const [cardType, setCardType] = useState<string>('客人卡');
  // 下拉框的值
  const [selectvalue, setselectvalue] = useState('');
  // input框输入查询
  const [Inputvalue, setInputvalue] = useState('');
  // 点击筛选房间状态
  const [clickvalue, setclickvalue] = useState('');
  // 退卡
  const [useMsg, setuseMsg] = useState<CardMSg[]>([]);
  // 套房换套房卡号上报操作
  const [IsChangeRooms, setIsChangeRooms] = useState(0);
  // 监听点击空白位子
  const inputRef = useRef<any>(null);
  // 判断 h5还是pc
  const [IsPhone, setIsPhone] = useState(false);

  const [H5Flag, setH5Flag] = useState(false);

  let RightClick: Element;

  useEffect(() => {
    // 页面加载获取全部房间
    getroom();
    // 获取房型下拉框
    RoomTypeList();
    // 获取楼栋
    getBuildlist();
    // 判断是否关闭了楼层  在加载组件时会取数据判断
    let Switchflag = localStorage.getItem('isFVisible');
    if (Switchflag == '1') {
      setIsFloorVisible(true);
    } else {
      setIsFloorVisible(false);
    }

    let buildID = localStorage.getItem('buiilName');
    if (buildID) {
      setChangeBuildNum(buildID);
    }
    const handleClick = (event: { target: any }) => {
      // 检查点击的元素是否在customContextMenu类名的元素之外
      if (isOutsideCustomContextMenu(event.target)) {
        if (
          event.target.className ==
            'ant-select-item ant-select-item-option ant-select-item-option-active' ||
          event.target.className == 'ant-modal-wrap' ||
          event.target.className == 'ant-modal-confirm-title'
        ) {
          return;
        }
        setcontextMenu(false);
      }
    };

    RightClick = document.getElementsByClassName('menustyle')[0];
    RightClick.addEventListener('scroll', debouncedHandleScroll);
    const isOutsideCustomContextMenu = (element: any) => {
      let currentElement = element;
      while (currentElement) {
        // 如果在遍历过程中找到具有customContextMenu类名的元素，则返回false
        if (currentElement.classList && currentElement.classList.contains('customContextMenu')) {
          return false;
        }
        // 继续向上遍历至父元素
        currentElement = currentElement.parentNode;
      }
      // 如果没有找到customContextMenu类名的元素，则返回true
      return true;
    };
    // 添加点击事件监听器到document，并确保它在冒泡阶段被捕获
    document.addEventListener('click', handleClick, true);
    // 清除函数

    // 需要最后渲染 不然元素还未加载
    setTimeout(() => {
      if (inputRef.current) {
        inputRef.current.blur();
      }
      let result = JSON.parse(localStorage.getItem('SetScaling'));
      if (result) {
        if (result.height == 100) return;
        setscaling((pre) => {
          return {
            ...pre, // 展开当前状态
            w: result.width, // 更新w的值
            h: result.height, // 假设我们也要增加h的值，增加5
            f: result.fontSize,
          };
        });
      }
    }, 150);
    os();
    return () => {
      document.removeEventListener('click', handleClick, true);
      RightClick.removeEventListener('scroll', debouncedHandleScroll, true);
    };
  }, []);
  var os = () => {
    var ua = navigator.userAgent,
      isWindowsPhone = /(?:Windows Phone)/.test(ua),
      isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
      isAndroid = /(?:Android)/.test(ua),
      isFireFox = /(?:Firefox)/.test(ua),
      isChrome = /(?:Chrome|CriOS)/.test(ua),
      isTablet =
        /(?:iPad|PlayBook)/.test(ua) ||
        (isAndroid && !/(?:Mobile)/.test(ua)) ||
        (isFireFox && /(?:Tablet)/.test(ua)),
      isPhone = /(?:iPhone)/.test(ua) && !isTablet,
      isPc = !isPhone && !isAndroid && !isSymbian;

    if (isAndroid || isPhone) {
      setIsPhone(true);
      setIsFloorVisible(true);
      console.log('手机 设置true');
    } else if (isTablet) {
      console.log('平板');
      setIsPhone(false);
    } else if (isPc) {
      setIsPhone(false);
      console.log('电脑');
    }
  };

  const handleOkFlag = () => {
    setuseflag(false);
    getroom();
  };

  const [sendMsg, setsendMsg] = useState<object | string>(''); // 发送消息 通过popos传递到了所有的子组件
  const [CardMessage, setCardMessage] = useState<any>(); // 接受消息
  const [type, setType] = useState<string>(''); // 成功后的提示消息 通过popos传递到了所有的子组件

  // 获取发卡人的信息和房间信息
  const [GetcardMsg, setGetcardMsg] = useState<CardMSg | any>();
  const [childRoomNum, setchildRoomNum] = useState<string>(''); //是否选中了套房
  const BULostCard = useSelector((state: any) => state.counter.BULostCard);
  // 判断是操作那个类型的卡
  useEffect(() => {
    console.log('监听', CardMessage);
    if (CardMessage) {
      if (CardMessage.result == 0) {
        // 发卡成功 需要调接口  sendMsg
        if (type == '客人卡,发卡成功') {
          console.log('进来', sendMsg);
          let data: CardMSg = {
            roomTypeName: GetcardMsg.tName ? GetcardMsg.tName : GetcardMsg.roomTypeName, // 套房类型是roomTypeName
            roomNo: GetcardMsg.roomNo,
            realName: GetcardMsg.username,
            roomName: GetcardMsg.roomName,
            mobile: GetcardMsg.phone,
            checkin: GetcardMsg.idcard,
            checkout: GetcardMsg.endtime,
            source: GetcardMsg.source,
            subRoomNo: childRoomNum,
            cardNum: CardMessage.cardid,
            bName: GetcardMsg.bName,
            rId: GetcardMsg.id,
            roomId: GetcardMsg.roomId,
            isHourlyRoom: parseInt(GetcardMsg.isHourlyRoom), // 是否是钟点房
            cmdInfo: JSON.stringify(sendMsg),
            isGroup: 0,
          };

          message.success(
            intl.formatMessage({ id: 'business.Guest card, card issuance successful' }),
          );
          roomfunc(data); // 发卡成功后存记录
        }
        if (type == '补卡成功') {
          message.success(
            intl.formatMessage({ id: 'business.The replacement card is successful' }),
          );
          roomfunc({ ...BULostCard, cardNum: CardMessage.cardid, id: 0, status: '1' }, true); // 发卡成功后存记录
          dispatch(changeBULostCard({}));
        }
        if (type == '套房换房') {
          RoomsSucceed();
        }
        if (type == '套房退房') {
          ReturnOrdinaryRoom(1);
        }
        if (type == '开始换房') {
          ReturnOrdinaryRoom(2);
        }
        if (type == '读卡成功') {
          readCard(CardMessage.cardid, CardMessage.cardclass, CardMessage);
        }
        if (type == '退卡成功前') {
          Checkcard(CardMessage.cardid, CardMessage.cardclass);
        }
        if (type == '退卡成功') {
          message.success(intl.formatMessage({ id: 'business.Card canceled successfully' }));
          ReturnRoomcard();
        }
        if (type == 'ChagngelostRoomCard') {
          const [res] = useDetermineCardType(CardMessage.cardclass);

          if (res == '挂失卡') {
            CleanCard();

            message.success(intl.formatMessage({ id: 'business.Card canceled successfully' }));
          } else {
            message.error(
              intl.formatMessage({ id: 'business.Return cardType message' }, { cardType: res }),
            );
          }
        }
        if (type == '校时卡,发卡成功') {
          message.success(type);
        }
        if (type == '洗卡成功') {
          message.success(type);
        }
        if (type == '校时卡前判断') {
          const [res] = useDetermineCardType(CardMessage.cardclass);
          if (CardMessage.losscardclass == 'guestcard') {
            message.error(intl.formatMessage({ id: 'business.This is Lost room card' }));
          } else {
            message.error(
              intl.formatMessage({ id: 'business.Return cardType message' }, { cardType: res }),
            );
          }
        }
        if (type == 'BefoerTuiCard') {
          if (CardMessage.hasOwnProperty('setlocktime')) {
            CleanCard();
            message.success(intl.formatMessage({ id: 'Card canceled successfully' }));
            setType('');
          } else {
            const [res] = useDetermineCardType(CardMessage.cardclass);
            message.error(
              intl.formatMessage({ id: 'business.Return cardType message' }, { cardType: res }),
            );
          }
        }
        if (type == 'BefoerLostRoomCard') {
          // SendlostRoomCard
          const [res] = useDetermineCardType(CardMessage.cardclass);
          if (CardMessage.losscardclass == 'guestcard') {
            message.error(intl.formatMessage({ id: 'business.This is Lost room card' }));
          } else {
            message.error(
              intl.formatMessage({ id: 'business.Return cardType message' }, { cardType: res }),
            );
          }
        }

        if (type == `挂失卡,发卡成功`) {
          message.success(intl.formatMessage({ id: 'business.Report lost card' }));
        }
        if (type == '换房') {
          ChangeRooms();
        }
        if (type == '续住') {
          ExtendedStay();
        }
        if (type == '上报退卡') {
          ReportCard();
        }
        if (type == '退卡成功前读卡') {
          readCardBefoer('1', CardMessage.cardid, CardMessage.cardclass);
        }

        if (type == '退卡成功前读卡2') {
          console.log('退卡成功前读卡2');
          readCardBefoer('2', CardMessage.cardid, CardMessage.cardclass);
        }
        if (type == '登记入住') {
          message.success(intl.formatMessage({ id: 'business.Checking in' }));
          setsendCardFlag(true);
          setIfSendCard(false);
          let data: CardMSg = {
            roomTypeName: GetcardMsg.tName ? GetcardMsg.tName : GetcardMsg.roomTypeName, // 套房类型是roomTypeName
            roomNo: GetcardMsg.roomNo,
            realName: GetcardMsg.username,
            roomName: GetcardMsg.roomName,
            mobile: GetcardMsg.phone,
            checkin: GetcardMsg.idcard,
            checkout: GetcardMsg.endtime,
            source: GetcardMsg.source,
            subRoomNo: childRoomNum,
            cardNum: CardMessage.cardid,
            bName: GetcardMsg.bName,
            rId: GetcardMsg.id,
            roomId: GetcardMsg.roomId,
            isHourlyRoom: parseInt(GetcardMsg.isHourlyRoom), // 是否是钟点房
            cmdInfo: JSON.stringify(sendMsg),
            isGroup: 1,
          };
          console.log(data);

          checkIn(data);
        }
        if (type == '上报读卡') {
          let id = '';
          if (CardMessage.cardclass == 'guestcard') {
            id = '1';
          } else if (CardMessage.cardclass == 'losscard') {
            id = '3';
          } else {
            let flag = IsManage(CardMessage.cardclass);
            id = flag ? '0' : '';
          }

          GetRoomMsg(CardMessage.cardid, Number(id));
        }
        if (type == '批量退卡') {
          ReturnCard(CardMessage.cardid);
        }
        if (type == '开始批量退卡') {
          CheckRoomcard(cardAndNum.card);
          setReturnText({
            code: 2,
            data: {},
          });
          setTimeout(() => {
            setReturnText({
              code: 0,
              data: {},
            });
            getroom();
          }, 200);
        }
      } else {
        if (type == 'BefoerLostRoomCard') {
          SendlostRoomCard();
        }
        if (type == '校时卡前判断') {
          TimerSer();
        } else if (CardMessage.uuid == 'autoreadcardid') {
          // 上报卡号
          if (CardMessage.cardid) {
            if (drawerVisit) {
              // 登记入住上报卡号发卡
              setIfSendCard(true);
            } else {
              // 上报卡号查询
              if (!isModalOpen && !BatchCardFlag) {
                console.log('上报卡号查询');

                let data1: ReadCard = { cardclass: 'readcard', uuid: '12345', isclear: '0' };
                setType('上报读卡');
                setsendMsg(data1);
              }
              // 套房换套房先退卡
              if (IsChangeRooms == 1) {
                ChangeRoomsReturnCard(CardMessage.cardid);
              } else if (IsChangeRooms == 2) {
                // 套房换普通房间
                OrdinaryRoom(CardMessage.cardid);
              }

              if (BatchCardFlag) {
                let data1: ReadCard = { cardclass: 'readcard', uuid: '12345', isclear: '0' };
                setType('批量退卡');
                setsendMsg(data1);
              }
            }
          } else {
            console.log('卡片移开');

            setIfSendCard(false);
            setshowDrawerFormflag(false);
          }
        } else {
          if (CardMessage.uuid != 'lostRoomCard') {
            // if (JSON.parse(lastMessage).result == 1001) {
            //   message.success('发卡器链接成功');
            // } else {
            //   if (JSON.parse(lastMessage).msg == intl.formatMessage({id:"Unknown card"})) {
            //     console.log(JSON.parse(lastMessage));

            //     if ('roomid' in JSON.parse(lastMessage)) {
            //       if (JSON.parse(lastMessage).cardclass == 'guestcard') {
            //         message.error(`${intl.formatMessage({ id: 'business.Not issued by our unit.' })}${getRoomNo(JSON.parse(lastMessage).roomid)}`);
            //       } else {
            //         message.error(intl.formatMessage({ id: 'business.Not issued by our unit.' }));
            //       }
            //     } else {
            //       message.error(intl.formatMessage({ id: 'business.Not issued by our unit.' }));
            //     }
            //   } else {
            //     message.error(JSON.parse(lastMessage).msg);
            //   }
            // }
            dispatch(changeCardname(' ')); // 如果读卡失败 不清除Cardname内容发卡按钮不能正常显示
          }
        }
      }
    }
  }, [CardMessage]);

  const [ReturnText, setReturnText] = useState({
    code: 0,
    data: {},
  });
  const ReturnCard = async (cardid: string) => {
    let data = await CheckoutUserRoom(cardid);

    if (!isEmptyObject(data.data)) {
      setReturnText({
        code: 1,
        data: data.data,
      });
      setcardAndNum({ num: '', card: data.data.cardNum });
      setTimeout(() => {
        let data = {
          cardclass: 'clearcard',
          lockclass: '1',
          shanqu: '1',
          pass: 'FFFFFFFFFFFF',
          uuid: '111974',
        };
        setType('开始批量退卡');
        setsendMsg(data);
      }, 800);
    } else {
      setReturnText({
        code: -1,
        data: {},
      });
    }
  };

  // 登记入住
  const checkIn = async (data: CardMSg) => {
    await TeamCheckin(data);
    getroom();
  };

  // 房号16进制转换10进制
  function getRoomNo(hexStr: string) {
    // 楼层的16进制字符串
    const floorHex = hexStr.substring(2, 4);
    // 房号的16进制字符串
    const roomHex = hexStr.substring(4, 6);

    // 将16进制字符串转换为10进制数字
    const floor = parseInt(floorHex, 16);
    const room = parseInt(roomHex, 16);

    // 如果房号小于10，则在前面补零
    const roomStr = room < 10 ? '0' + room : room.toString();

    // 将楼层和房号拼接起来
    return floor.toString() + roomStr;
  }

  // const [NoMessage,setNoMessage] = useState(false)
  // Now 当前房间信息 Next换房目标信息
  const { Now, Next } = useSelector((state: any) => state.counter.ChangeRoomList);
  const [NumId, setNumId] = useState(0);
  const ChangeRoomsReturnCard = (card: string) => {
    let data = Now.find((item: { cardNum: string }) => item.cardNum == card);
    let SendData = JSON.parse(data.cmdInfo);
    let NextRoom = {
      ...SendData,  
      roomid: Next.childRooms[NumId].roomId,
      roomName: Next.childRooms[NumId].roomName,
    };
    if (data) {
      setType('套房换房');
      setsendMsg(NextRoom);
      setGetcardMsg({
        ...data,
        subRoomNo: Next.childRooms[NumId].roomName,
        roomName: Next.roomName,
        roomNo: Next.roomNo,
        roomId: Next.roomId,
        cardNum: card,
        cmdInfo: JSON.stringify(RightClick),
      });
      localStorage.setItem('RecardNum', card);
    } else {
      message.error(intl.formatMessage({ id: "Card number doesn't match." }));
    }
  };

  // 套房换套房覆盖发房卡
  const RoomsSucceed = async () => {
    if (NumId == 0) {
      let data: any = await UsercheckinList(GetcardMsg);
      if (data.code == 0) {
        getroom();
        setshowDrawerFormflag(false);
        message.success(intl.formatMessage({ id: 'Successfully moved to a new place' }));
      }
    } else {
      let { id, ...res } = GetcardMsg;
      let data: any = await IssuingCheckin(res);

      if (data.code == 0) {
        getroom();
        setshowDrawerFormflag(false);
        message.success(intl.formatMessage({ id: 'Successfully moved to a new place' }));
        dispatch(setChangeRoomList({}));
        setNumId(0);
      }
    }
  };

  // 套房换普通房 先退卡在发卡
  const OrdinaryRoom = (card: string) => {
    let data = Now.find((item: { cardNum: string }) => item.cardNum == card);
    if (data) {
      let data = {
        cardclass: 'clearcard',
        lockclass: '1',
        shanqu: '1',
        pass: 'FFFFFFFFFFFF',
        uuid: '111974',
      };
      setType('套房退房');
      setsendMsg(data);
      setcardAndNum({ card: card, num: '' });
      localStorage.setItem('RecardNum', card);
    } else {
      message.error(intl.formatMessage({ id: "Card number doesn't match." }));
    }
  };

  const ReturnOrdinaryRoom = async (num: number) => {
    if (num == 1) {
      let res: any = await CheckRoomcard(cardAndNum.card);
      if (res.code == 0) {
        dispatch(increment());
        setNumId((prevNumId) => prevNumId + 1);
      }
    } else if (num == 2) {
      let data = await UsercheckinList(BULostCard);
      if (data.code == 0) {
        getroom();
        message.success(intl.formatMessage({ id: 'Successfully moved to a new place' }));
        setshowDrawerFormflag(false);
        dispatch(changeBULostCard({}));
      }
    }
  };

  // 登记入住
  const [sendCardFlag, setsendCardFlag] = useState(false);

  // 手牌上报点击退房
  const ReportCard = async () => {
    let data: any = await CheckRoomcard(ChangeRoomsMsg.cardNum);
    if (data.code == 0) {
      message.success(intl.formatMessage({ id: 'Card canceled successfully' }));
      getroom();
      setshowDrawerFormflag(false);
    }
  };

  const [ChangeRoomsMsg, setChangeRoomsMsg] = useState<CardMSg>({});
  const ChangeRooms = async () => {
    let data: any = await UsercheckinList([ChangeRoomsMsg]);
    if (data.code == 0) {
      getroom();
      message.success(intl.formatMessage({ id: 'Successfully moved to a new place' }));
      setshowDrawerFormflag(false);
    } else {
      message.error(data.msg);
    }
  };

  // 续住
  const ExtendedStay = async () => {
    let data: any = await IssuingCheckin(ChangeRoomsMsg);
    if (data.code == 0) {
      message.success(intl.formatMessage({ id: 'Successfully extended your stay card' }));
      getroom();
      setshowDrawerFormflag(false);
    }
  };

  const [api, contextHolder] = notification.useNotification();
  const GetRoomMsg = async (cardid: string, num: number) => {
    if (num == 1) {
      // 客人卡
      let data: any = await CheckoutUserRoom(cardid);
      const IsObjFlag = isEmptyObject(data.data);
      if (!IsObjFlag) {
        setdataRoomMsg(data);
        setshowDrawerFormflag(true);
      } else {
        api.open({
          message: intl.formatMessage({ id: 'Empty card' }),
          icon: <InfoCircleOutlined style={{ color: 'red' }} />,
          description: '',
          duration: 4.5,
          placement: 'topRight',
        });
      }
    } else if (num == 0) {
      // 管理卡
      let data = await GetAdminCard(cardid);
      const IsObjFlag = isEmptyObject(data.data);
      if (!IsObjFlag) {
        setdataRoomMsg(data);
        setshowDrawerFormflag(true);
      }
    } else {
      // 挂失卡
      let data = await getLogLossCardCardNum(cardid);
      const IsObjFlag = isEmptyObject(data.data);
      if (!IsObjFlag) {
        setdataRoomMsg(data);
        setshowDrawerFormflag(true);
      }
    }
  };

  // 房间挂失
  const LostRoomNum = useSelector((state: any) => state.counter.LostRoomNum);
  const LostRoomID = useSelector((state: any) => state.counter.LostRoomID);
  const SendlostRoomCard = async () => {
    const endOfDay = dayjs().endOf('day');
    let result = await lostRoomCard(LostRoomNum);

    let data = {
      cardclass: 'losscard',
      uuid: 'guestcard',
      roomid: '',
      losstype: '2',
      losscardclass: 'guestcard',
      begintime: result.data.loss_expire_time,
      endtime: endOfDay.format('YYYY-MM-DD HH:mm:ss'),
      custontime: result.data.custom_time,
    };

    let res = await Write_LossCard(data);

    setCardMessage(res);
    setType(`挂失卡,发卡成功`);
  };

  const [cardtime, setCardtime] = useState<number>(10);
  // 校时卡 发卡
  const TimerSer = async () => {
    let Result = await GetSetcardTimer(cardtime);
    if (Result.code == 0) {
      const dataMSG: any = {
        cardclass: 'setcard',
        uuid: 'setcard',
        setlocktime: Result.data.now,
      };

      let res = await SetupCard(dataMSG);
      setCardMessage(res);
      setsendMsg(dataMSG);
      setType('校时卡,发卡成功');
    }
  };
  const dispatch = useDispatch();
  // 房间信息退卡   多张卡时对卡不关闭弹窗
  const [cardAndNum, setcardAndNum] = useState({
    num: '',
    card: '',
  });

  // 退卡
  const GetNowCardMsg = useSelector((state: any) => state.counter.GetNowCardMsg);
  const readCardBefoer = async (num: string, card: string, type: string): Promise<any> => {
    console.log(GetNowCardMsg.cardNum, num, card, type);

    if (type != 'guestcard')
      return message.error(intl.formatMessage({ id: 'business.This card is not for guests' }));
    if (GetNowCardMsg.cardNum != card)
      return message.error(
        intl.formatMessage({ id: "business.This card isn't the current room card" }),
      );
    let res = await CleanCard();
    setCardMessage(res);

    setType('退卡成功');
    setcardAndNum({ num: num, card: card });
  };
  // 驱动返回成功后才能调用这个方法删除记录
  const ReturnRoomcard = async () => {
    let res = await CheckRoomcard(cardAndNum.card);
    dispatch(increment());
    dispatch(setGetNowCardMsg({}));
    if (cardAndNum.num == '2') {
      if (res.code == 0) {
        handleOk();
      }
    }
  };
  const RoomChinkList = useSelector((state: any) => state.counter.RoomChinkList);
  const TrueList = useSelector((state: any) => state.counter.TrueList); // 房间发卡选中的数据
  const ChinkListFlag = useSelector((state: any) => state.counter.ChinkListFlag);

  const [GETID, setGETID] = useState('');
  const [IScheckInFlag, setIScheckInFlag] = useState(false);
  // 提交发卡记录
  const roomfunc = async (data: CardMSg, flag?: boolean) => {
    if (flag == true) {
      // 补卡提交记录
      let res = await IssuingCheckin(data);
      if (res.code == 0) {
        dispatch(increment()); // 发卡成功后table列表组件需要更新 使用redux来更新状态
      }
      return;
    }
    // 干净房发第一张卡
    if (IScheckInFlag == false && ChinkListFlag == true) {
      const newRoomChinkList = RoomChinkList.map((item: { UUID: string }) => {
        if (item.UUID == TrueList.UUID) {
          return { ...data, status: '1', issuingTime: dayjs().format('YYYY-MM-DD HH:mm:ss') };
        } else {
          return item;
        }
      });

      let result: any = await UsercheckinList(newRoomChinkList); // 保存多条记录的接口  用于房间第一次时调用 后续才会调下面的IssuingCheckin接口
      if (result.code == 0) {
        dispatch(changeRoomChinkList([]));
        dispatch(changeTrueList({}));
        dispatch(increment());
        dispatch(changeChinkListFlag(false));
        setchildRoomNum('');
      }
    } else {
      // 入住房继续发卡
      let res: any = await IssuingCheckin({ ...data, id: parseInt(GETID) });
      if (res.code == 0) {
        setchildRoomNum('');
        dispatch(increment()); // 发卡成功后table列表组件需要更新 使用redux来更新状态
      }
    }
  };

  // 读卡弹窗
  const readCard = async (card: string, cardclass: string, Setcard?: any) => {
    console.log('传值', card, cardclass, Setcard);

    // 客人卡
    if (cardclass === 'guestcard') {
      setCardType(intl.formatMessage({ id: 'card.Guest Card' }));
      let data: any = await CheckoutUserRoom(card);
      console.log('data =>', data.data);
      if (data.code === 0) {
        // 打开弹窗
        if (data.data.id) {
          setuseMsg(data.data);
          setuseflag(true);
        } else {
          message.error(intl.formatMessage({ id: 'business.Unknown card' }));
        }
      }
    }
    // 挂失卡
    else if (cardclass === 'losscard') {
      setCardType(intl.formatMessage({ id: 'business.Lost Card' }));
      let data = await getLogLossCardCardNum(card);
      if (data.data.cardNum) {
        setuseMsg(data.data);
        setuseflag(true);
      } else {
        message.error(intl.formatMessage({ id: 'business.Unknown card' }));
      }
    } else if (cardclass == 'setcard') {
      setCardType(intl.formatMessage({ id: 'card.Setup card' }));
      setuseMsg(Setcard);
      setuseflag(true);
      message.error(intl.formatMessage({ id: 'business.This card is a system card' }));
    }
    // 管理卡
    else {
      setCardType(intl.formatMessage({ id: 'card.Management card' }));
      let data = await GetAdminCard(card);
      if (data.data.cardNum !== '' && data.data.cardNum) {
        setuseMsg(data.data);
        setuseflag(true);
      } else {
        message.error(intl.formatMessage({ id: 'business.Unknown card' }));
      }
    }
  };
  function isEmptyObject(obj: {}) {
    return typeof obj === 'object' && Object.keys(obj).length === 0;
  }
  // 退房前先弹框
  const Checkcard = async (card: string, cardclass: string) => {
    if (cardclass == 'losscard' || cardclass == 'guestcard') {
      let data: any = await CheckoutUserRoom(card);
      if (data.code == 0) {
        const IsObjFlag = isEmptyObject(data.data); // 判断是否是空对象
        // 打开弹窗
        if (IsObjFlag == false) {
          data.data.status = 3;
          let result = data.data;
          showModal(result);
        } else {
          let data = {
            cardclass: 'clearcard',
            lockclass: '1',
            shanqu: '1',
            pass: 'FFFFFFFFFFFF',
            uuid: '111974',
          };
          setsendMsg(data);
          message.success(intl.formatMessage({ id: 'business.Card canceled successfully' }));
        }
      }
    } else if (cardclass == 'setcard') {
      message.error(intl.formatMessage({ id: 'business.This card is a setup card' }));
      dispatch(changeCardname(' '));
    } else {
      if (cardclass) {
        const [res] = useDetermineCardType(cardclass);
        message.error(
          intl.formatMessage({ id: 'business.Return cardType message' }, { cardType: res }),
        );
        dispatch(changeCardname(' '));
      }
    }
  };

  // 打开单个房间 并吧房间信息传入子组件
  const showModal = (item: RoomList) => {
    setSelectedItem(item);

    if (IsPhone) return setH5Flag(true);
    setIsModalOpen(true);
    setshowDrawerFormflag(false);
    if (item.status == '3') {
      setIScheckInFlag(true);
    } else {
      setIScheckInFlag(false);
    }
  };

  //关闭弹窗 并吧这个方法传入子组件
  const handleOk = useCallback(() => {
    setH5Flag(false);
    setIsModalOpen(false);
    getroom();
    dispatch(changeCardname(' ')); // 判断只有点击退卡时才会显示退卡按钮
  }, []);

  // 获取房间
  const [RoomMsglist, setRoomMsglist] = useState<RoomJIa[]>([]);
  const getroom = async () => {
    let buildID = localStorage.getItem('buiilName');
    let { data } = await GetAllRoomList({
      b_id: buildID ? buildID : ChangeBuildNum,
      name: '',
      Params: '',
      id: '',
    });
    if (data.list) {
      const list = RoomStatus(data.list, RoomArr); // 房态数据
      const list2 = useArrsort(data.list); // 房间数据
      // 计算当前有无房间过期 如果已过期 设置状态为9
      setRoomAllList(list2);
      list2.map((item: { list: any[] }) => {
        return item.list.forEach(
          (l: { checkInEndTime: string | number | Date; status: number }) => {
            if (isPastflag(l.checkInEndTime)) {
              l.status = 9;
            }
          },
        );
      });
      setlist2(data.list);
      setRoomMsglist(list);
      setList(list2);
      localStorage.removeItem('RoomList');
      localStorage.setItem('RoomList', JSON.stringify(list));
    } else {
      message.error(
        intl.formatMessage({ id: 'Please contact the admin to get the room information' }),
      );
    }
    if (localStorage.getItem('isFVisible') == '2') {
      if (data.list) {
        setlist2(data.list);
      }
    }
  };
  // 获取房型
  const RoomTypeList = async () => {
    let { data } = await getRoomTypeList();

    if (data.list) {
      let type = data.list.map((item: { name: string }) => {
        return item.name;
      });
      setRoomType(type);
      let type_id = data.list.map((item: { id: string; name: string }) => {
        return {
          id: item.id,
          name: item.name,
        };
      });

      settypeid(type_id);
    }
  };
  // 仅在组件挂载时运行 c
  const RoomArr: RoomJIa[] = [
    {
      name: intl.formatMessage({ id: 'business.Stay' }),
      num: 3,
      RoomNum: '',
    },
    {
      name: intl.formatMessage({ id: 'business.Empty Purity' }),
      num: 1,
      RoomNum: '',
    },
    {
      name: intl.formatMessage({ id: 'business.Empty Dirty' }),
      num: 2,
      RoomNum: '',
    },

    {
      name: intl.formatMessage({ id: 'business.Maintenance' }),
      num: 4,
      RoomNum: '',
    },
  ];
  const RoomArr2 = [
    {
      name: intl.formatMessage({ id: 'business.redcard' }),
      num: 10,
    },
    {
      name: intl.formatMessage({ id: 'business.Return the card' }),
      num: 5,
    },
    // {
    //   name: '续卡',
    //   num: 6,
    // },
    // {
    //   name: '洗卡',
    //   num: 30,
    // },
  ];

  // 是否楼层显示
  const handleSwitchChange = (checked: boolean | ((prevState: boolean) => boolean)) => {
    setIsFloorVisible(checked);
    setTimeout(() => {
      let result = JSON.parse(localStorage.getItem('SetScaling'));
      if (result) {
        if (result.height == 100) return;
        setscaling((pre) => {
          return {
            ...pre, // 展开当前状态
            w: result.width, // 更新w的值
            h: result.height, // 假设我们也要增加h的值，增加5
            f: result.fontSize,
          };
        });
      }
    });
  };

  // 监听是否选中了按楼栋显示
  useEffect(() => {
    if (isFloorVisible == true) {
      localStorage.setItem('isFVisible', '1');
    } else {
      localStorage.setItem('isFVisible', '2');
    }
  }, [isFloorVisible]);

  // 持卡快捷操作 (查卡 退卡 续卡)
  const getCardchange = async (name: string) => {
    console.log('name', name);
    dispatch(changeCardname(name));

    if (name == '退卡' || name == 'Return card') {
      let res = await Read_Card();
      if (res.result != 0) return message.error(res.msg);
      setCardMessage(res);

      console.log('res', res);

      setType('退卡成功前');
    }
    if (name == '读卡' || name == 'ReadCard') {
      let res = await Read_Card();
      if (res.result != 0) return message.error(res.msg);
      setCardMessage(res);

      console.log('res', res);
      setType(`读卡成功`);
    }
    if (name == '续卡') {
      let res = await Read_Card();
      if (res.result != 0) return message.error(res.msg);
      setCardMessage(res);

      console.log('res', res);

      setType('退卡成功前');
    }
  };

  // 房型下拉框赛选
  const ChangeRoomTypeSelect = async (newValue: string) => {
    let id: string = ' ';
    typeid.forEach((item: any) => {
      if (item.name == newValue) {
        id = item.id.toString();
      }
      setselectvalue(id.toString());
    });
    const [list, arr2, list2] = await FlagSwitch(
      Inputvalue,
      id.toString(),
      clickvalue,
      ChangeBuildNum,
      RoomArr,
    );
    setList(arr2);
    setlist2(list);
    setRoomMsglist(list2);
  };

  // 搜索房间
  const SearchRoom = async (value: string) => {
    setInputvalue(value);
    if (value == '') {
      getroom();
    } else {
      const [list, arr2, list2] = await FlagSwitch(
        value,
        selectvalue,
        clickvalue,
        ChangeBuildNum,
        RoomArr,
      );
      setList(arr2);
      setlist2(list);
      setRoomMsglist(list2);
    }
  };
  // 点击房态赛选和变化颜色
  const [form] = Form.useForm();

  const [selectedRoom, setSelectedRoom] = useState<any>({});
  const getcolor = async (name: string, number: number) => {
    //
    setclickvalue(number.toString());
    const divs: any = document.getElementsByClassName('biglist');
    for (let i = 0; i < divs.length; i++) {
      divs[i].style.backgroundColor = '#fff';
    }
    // 设置当前点击的房间背景颜色，除非它已经被选中
    if (selectedRoom[name]) {
      setclickvalue(' ');
      setSelectedRoom({}); // 重置状态
      getroom(); // 点击取消该选中状态 请求全部数据
    } else {
      const div: any = document.getElementById(name);
      div.style.backgroundColor = 'rgb(204, 202, 202)';
      setSelectedRoom({ [name]: true }); // 更新状态
      const [list, arr2, list2] = await FlagSwitch(
        Inputvalue,
        selectvalue,
        number.toString(),
        ChangeBuildNum,
        RoomArr,
      );
      setList(arr2);
      setlist2(list);
      setRoomMsglist(list2);
    }
  };

  // 获取楼栋发
  const [BuildList, setBuildList] = useState([]);
  const [buildname, setbuildname] = useState('');
  const [ChangeBuildNum, setChangeBuildNum] = useState('');
  // 如果buildID因为删除了,会造成楼栋ID的改变,还能获取到buildID而filter找不到数据就返回了空数组 所有需要判断多层
  const getBuildlist = async () => {
    const data = await getBuildingsList();
    if (data.data.list) {
      let buildID = localStorage.getItem('buiilName');
      if (buildID) {
        let buildName = data.data.list.filter((item: { id: string | null }) => item.id == buildID);
        if (buildName.length) {
          //  选择第一条
          setbuildname(buildName[0].name);
        } else {
          localStorage.removeItem('buiilName');
          setbuildname(data.data.list[0].name);
          setChangeBuildNum(data.data.list[0].id);
        }
      } else {
        setbuildname(data.data.list[0].name);
        setChangeBuildNum(data.data.list[0].id);
      }
      setBuildList(data.data.list);
    }
  };
  // 选择楼栋查询数据
  const ChangeBuild = async (value: string) => {
    console.log('value', value);

    setChangeBuildNum(value);
    setbuildname(value);
    localStorage.setItem('buiilName', value);
    const [list, arr2, list2] = await FlagSwitch(
      Inputvalue,
      selectvalue,
      clickvalue,
      value,
      RoomArr,
      true,
    );
    setList(arr2);
    setlist2(list);
    setRoomMsglist(list.length ? list2 : []);
  };

  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0, status: '' });
  const [contextMenu, setcontextMenu] = useState(false);
  const [SelectRoom, setSelectRoom] = useState({
    roomName: '',
    status: 0,
    roomId: '',
    checkInPeople: '',
  });

  const [GetscrollTop, setGetscrollTop] = useState(0);

  const handleScroll = () => {
    setcontextMenu(false);
    setGetscrollTop(RightClick.scrollTop);
  };

  const debouncedHandleScroll = lodash.debounce(handleScroll, 400);
  const handleContextMenu = (
    event: React.MouseEvent<HTMLDivElement, MouseEvent>,
    RoomItem: any,
  ) => {
    event.preventDefault();
    setcontextMenu(true);
    let sta =
      RoomItem.status == '1'
        ? '干净房'
        : RoomItem.status == '2'
          ? '脏房'
          : RoomItem.status == '3'
            ? '入住房'
            : RoomItem.status == '4'
              ? '维修房'
              : '';
    setContextMenuPosition({ x: event.clientX, y: event.clientY + GetscrollTop, status: sta });
    setSelectRoom(RoomItem);
  };

  const [showDrawerFormflag, setshowDrawerFormflag] = useState(false); // 上报卡号的弹窗
  const [dataRoomMsg, setdataRoomMsg] = useState(); // 上报卡号对应的数据
  const [RoomAllList, setRoomAllList] = useState([]);

  // 发卡历史记录
  const NocardTetrunRoom = () => {
    console.log('查看记录', SelectRoom);
  };
  // 登记入住
  const [drawerVisit, setdrawerVisit] = useState(false);
  // 登记如何查看是否上报卡号
  const [IfSendCard, setIfSendCard] = useState(false);
  const WhillCheckIn = () => {
    setdrawerVisit(true);
  };

  // 入住记录
  const [ChinkHistoryflag, setChinkHistoryflag] = useState(false);
  const ChinkHistory = () => {
    setChinkHistoryflag(true);
  };
  // const [IsShowConter, setIsShowConter] = useState(false)
  // const handleDragStart = (e: React.DragEvent<HTMLDivElement>, item: RoomList, index: number) => {
  //   // 开启拖拽 关闭鼠标右键和鼠标悬浮
  //   setIsShowConter(true)
  //   setcontextMenu(false);
  //   e.dataTransfer.setData('text/plain', JSON.stringify({ item }));
  // };

  // const handleDrop = (e: React.DragEvent<HTMLDivElement>, InItem: RoomList): any => {
  //   // 结束拖拽后开启鼠标右键和鼠标悬浮
  //   setIsShowConter(false)
  //   e.preventDefault();
  //   // 获取拖拽的数据
  //   const data = JSON.parse(e.dataTransfer.getData('text/plain'));
  //   const { item } = data;
  //   console.log(item)
  //   if (item.roomName == InItem.roomName) return
  //   if (InItem.status == "3") return message.error("危险操作")

  //   useDeleteConfirm(`换房 -- 请将房卡放置发卡器上`, `是否将【${item.roomName}】换到【${InItem.roomName}】`, (val) => {
  //     if (val) {
  //       message.success("尽情期待😊~")
  //     }
  //   })
  // };
  const refscaling = useRef(null);
  const [scaling, setscaling] = useState({
    w: 8.5, // 宽度
    h: 10, // 高度
    f: 14, // 字体大小
  });

  const big = () => {
    if (scaling.h == 2) return;
    setscaling((pre) => {
      return {
        ...pre, // 展开当前状态
        w: pre.w + 0.5, // 更新w的值
        h: pre.h + 1, // 假设我们也要增加h的值，增加5
        f: pre.f + 2,
      };
    });
    let WidthPX = scaling.w + 0.5;
    let HeigPX = scaling.h + 1;
    let Heigf = scaling.f + 2;
    localStorage.setItem(
      'SetScaling',
      JSON.stringify({ width: WidthPX, height: HeigPX, fontSize: Heigf }),
    );
  };
  const small = () => {
    if (scaling.h == 5) return;
    setscaling((pre) => {
      return {
        ...pre, // 展开当前状态
        w: pre.w - 0.5, // 更新w的值
        h: pre.h - 1, // 假设我们也要增加h的值，增加5
        f: pre.f - 2,
      };
    });
    let WidthPX = scaling.w - 0.5;
    let HeigPX = scaling.h - 1;
    let Heigf = scaling.f - 2;
    localStorage.setItem(
      'SetScaling',
      JSON.stringify({ width: WidthPX, height: HeigPX, fontSize: Heigf }),
    );
  };

  const [BatchCardFlag, setBatchCardFlag] = useState(false);

  const BatchCard = () => {
    setBatchCardFlag(true);
  };

  return (
    <div className="yingye">
      {H5Flag && <H5Model H5Flag={H5Flag} userMsg={selectedItem} handleOk={handleOk} />}

      {/* 批量退卡 */}
      {BatchCardFlag && (
        <BatchCardReturns
          BatchCardFlag={BatchCardFlag}
          ReturnText={ReturnText}
          setBatchCardFlag={setBatchCardFlag}
        />
      )}
      {/* 入住记录弹窗  */}
      {ChinkHistoryflag && (
        <ChinkHistoryModal
          ChinkHistoryflag={ChinkHistoryflag}
          setChinkHistoryflag={setChinkHistoryflag}
        />
      )}
      {/* 登记入住 */}
      {drawerVisit && (
        <Addoccupants
          drawerVisit={drawerVisit}
          setdrawerVisit={setdrawerVisit}
          list2={list2}
          setsendMsg={setsendMsg}
          setType={setType}
          sendCardFlag={sendCardFlag}
          setsendCardFlag={setsendCardFlag}
          IfSendCard={IfSendCard}
          setGetcardMsg={setGetcardMsg}
        />
      )}

      {/* 上报卡号弹窗操作  */}
      {showDrawerFormflag && !isModalOpen && (
        <ShowDrawerForm
          showDrawerFormflag={showDrawerFormflag}
          setshowDrawerFormflag={setshowDrawerFormflag}
          dataRoomMsg={dataRoomMsg}
          RoomAllList={RoomAllList}
          list2={list2}
          setsendMsg={setsendMsg}
          setType={setType}
          setChangeRoomsMsg={setChangeRoomsMsg}
          setIsChangeRooms={setIsChangeRooms}
          setGetcardMsg={setGetcardMsg}
          setNumId={setNumId}
        />
      )}
      {/* 查卡弹出框 */}
      {useflag && (
        <UserMsgModel
          useflag={useflag}
          handleOkFlag={handleOkFlag}
          useMsg={useMsg}
          setsendMsg={setsendMsg}
          setType={setType}
          cardType={cardType}
        />
      )}
      <Card
        bordered={false}
        className="menustyle"
        style={{
          width: '100%',
          marginTop: '-5px',
          height: '90vh',
          overflowY: 'auto',
          msOverflowStyle: 'none',
          scrollbarWidth: 'none',
        }}
      >
        {/* 头部导航栏 */}
        <div className="SeachTop">
          <div
            style={{
              position: IsPhone ? 'static' : 'absolute', // H5用默认定位，PC用绝对定位
              right: IsPhone ? undefined : '0', // H5移除right定位
              display: 'flex',
              alignItems: 'center',
            }}
          >
            <div style={{ display: 'flex' }}>
              {RoomMsglist.map((item: RoomJIa) => {
                let className = 'yuan';
                switch (item.name) {
                  case '空净':
                    className += ' cleanRoom';
                    break;
                  case 'Empty Purity':
                    className += ' cleanRoom';
                    break;
                  case 'Stay':
                    className += ' singleRoom';
                    break;

                  case '入住':
                    className += ' singleRoom';
                    break;
                  case '空脏':
                    className += ' doubleRoom';
                    break;
                  case 'Empty Dirty':
                    className += ' doubleRoom';
                    break;
                  case '套房':
                    className += ' suiteRoom';
                    break;
                  case '维修':
                    className += ' maintenanceRoom';
                    break;
                  case 'Maintenance':
                    className += ' maintenanceRoom';
                    break;
                  default:
                    // 默认样式
                    className += ' defaultRoom';
                }

                return (
                  <div
                    key={item.num}
                    id={item.name}
                    className="biglist AABB"
                    onClick={() => {
                      getcolor(item.name, item.num);
                    }}
                  >
                    <>
                      <div style={{ display: 'flex' }} className="onelist">
                        <div className={className}></div>
                        {!IsPhone ? item.name : ''}
                      </div>
                      <div>
                        {' '}
                        {item.RoomNum == '' ? (
                          ' - '
                        ) : (
                          <span style={{ marginLeft: '2px', fontSize: '18px' }}>
                            {item.RoomNum}
                          </span>
                        )}{' '}
                        {!IsPhone ? intl.formatMessage({ id: 'business.Space' }) : ''}
                      </div>
                    </>
                  </div>
                );
              })}
            </div>

            <div style={{ marginBottom: '10px' }}>
              {/* 楼层显示 */}
              {!IsPhone && (
                <>
                  <Switch
                    checkedChildren={intl.formatMessage({ id: 'business.indicate' })}
                    unCheckedChildren={intl.formatMessage({ id: 'business.close' })}
                    checked={isFloorVisible}
                    onChange={handleSwitchChange}
                    style={{ marginTop: 5, maxWidth: '70px' }}
                  />{' '}
                  &emsp;
                  {/* <Input
                    placeholder="请输入缩放比例"
                    // disabled
                    ref={inputRef}
                    style={{ maxWidth: '180px' }}
                    addonBefore={
                      <button
                        style={{ border: 'none', backgroundColor: '#FAFAFA', width: 10 }}
                        onClick={small}
                      >
                        -
                      </button>
                    }
                    addonAfter={
                      <button style={{ border: 'none', backgroundColor: '#FAFAFA' }} onClick={big}>
                        +
                      </button>
                    }
                    value={`${intl.formatMessage({ id: 'business.scaling' })}${scaling.w - 40}%`}
                  /> */}
                </>
              )}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {!IsPhone &&
              RoomArr2.map((item) => {
                return (
                  <div key={item.num} onClick={() => getCardchange(item.name)}>
                    <Button
                      type={item.name == '洗卡' ? 'dashed' : 'primary'}
                      danger={item.name == '退卡' || item.name == 'Return card'}
                      style={{ marginBottom: 10 }}
                    >
                      {' '}
                      {item.name}
                    </Button>{' '}
                    &nbsp;
                  </div>
                );
              })}
            <div style={{ marginBottom: 10 }}>
              {/* <Button style={{ backgroundColor: '#4096FF', color: '#fff' }} onClick={WhillCheckIn}>
                {intl.formatMessage({ id: 'business.CheckIn' })}
              </Button>{' '}
              &nbsp;
              <Button
                type="primary"
                danger
                onClick={() => {
                  setReturnText({
                    code: 0,
                    data: {},
                  });
                  BatchCard();
                }}
              >
                {intl.formatMessage({ id: 'business.BatchCardReturns' })}
              </Button> */}
              &nbsp;
              {!IsPhone && (
                <Button
                  style={{ backgroundColor: '#4096FF', color: '#fff' }}
                  onClick={ChinkHistory}
                >
                  {intl.formatMessage({ id: 'business.CheckInRecord' })}
                </Button>
              )}
            </div>{' '}
            &nbsp;
            <div style={{ marginBottom: 8 }}>
              <ProForm
                form={form}
                layout={'inline'}
                submitter={{
                  searchConfig: {
                    resetText: '重置',
                    submitText: '提交',
                  },
                  resetButtonProps: { style: { display: 'none' } },
                  render: () => [],
                }}
              >
                {!IsPhone ? ( // PC端布局
                  <>
                    {BuildList.length > 1 && (
                      <Select
                        style={{ width: 140 }}
                        options={BuildList.map(({ id, name }) => {
                          return { value: id, label: name };
                        })}
                        placeholder={intl.formatMessage({
                          id: 'business.Please select a building',
                        })}
                        onChange={ChangeBuild}
                        value={buildname}
                      />
                    )}
                    <Input
                      placeholder={intl.formatMessage({
                        id: 'business.Please enter your room number',
                      })}
                      style={{ width: 150 }}
                      onChange={(e) => SearchRoom(e.target.value.replace(/\s|\D/g, ''))}
                    />{' '}
                    &nbsp;
                    <ProFormSelect
                      options={RoomType.map((label) => ({ value: label, label }))}
                      allowClear={false}
                      name="wd"
                      style={{ width: 140 }}
                      placeholder={intl.formatMessage({ id: 'business.Please select a roomType' })}
                      onChange={ChangeRoomTypeSelect}
                    />
                  </>
                ) : (
                  // H5端布局
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {BuildList.length > 1 && (
                      <div style={{ width: 'calc(50% - 4px)' ,marginRight: "5px" }}>
                        <Select
                          options={BuildList.map(({ id, name }) => {
                            return { value: id, label: name };
                          })}
                          placeholder={intl.formatMessage({
                            id: 'business.Please select a building',
                          })}
                          onChange={ChangeBuild}
                          value={buildname}
                        /> 
                      </div>
                    )}
                    <div style={{ width: 'calc(50% - 4px)' }}>
                      <Input
                        placeholder={intl.formatMessage({
                          id: 'business.Please enter your room number',
                        })}
                        style={{ width: 150 }}
                        onChange={(e) => SearchRoom(e.target.value.replace(/\s|\D/g, ''))}
                      />&nbsp;
                    </div>
                    <div style={{ width: 'calc(50% - 4px)' }}>
                      <ProFormSelect
                        options={RoomType.map((label) => ({ value: label, label }))}
                        allowClear={false}
                        name="wd"
                        style={{ width: 140 }}
                        placeholder={intl.formatMessage({
                          id: 'business.Please select a roomType',
                        })}
                        onChange={ChangeRoomTypeSelect}
                      />
                    </div>
                  </div>
                )}
              </ProForm>
            </div>
          </div>
        </div>

        {isModalOpen && (
          <ModalComponent
            isModalOpen={isModalOpen}
            handleOk={handleOk}
            selectedItem={selectedItem}
            setsendMsg={setsendMsg}
            setType={setType}
            setGetcardMsg={setGetcardMsg}
            setchildRoomNum={setchildRoomNum}
            setGETID={setGETID}
            setCardtime={setCardtime}
            setCardMessage={setCardMessage}
          />
        )}
        {/* 鼠标右键菜单 */}
        {contextMenu && (
          <div
            className="customContextMenu"
            style={{
              position: 'absolute',
              top: contextMenuPosition.y - 50,
              left: contextMenuPosition.x - 15,
              zIndex: 99999,
            }}
          >
            {(SelectRoom.status == 3 || SelectRoom.status == 2) && (
              <div
                style={{ width: 130, display: 'flex', alignItems: 'center' }}
                onClick={async () => {
                  let data: any = await ChangeRoomType({
                    room_id: SelectRoom.roomId,
                    status: 1,
                  });
                  if (data.code == 0) {
                    getroom();
                    setcontextMenu(false);
                  }
                }}
              >
                <div className="yuan cleanRoom"></div>
                <div className="RoomText AABB">
                  {intl.formatMessage({ id: 'business.Set Clean' })}
                </div>
              </div>
            )}

            {SelectRoom.status != 3 && SelectRoom.status != 2 && (
              <div
                style={{ width: 130, display: 'flex', alignItems: 'center' }}
                onClick={async () => {
                  let data: any = await ChangeRoomType({
                    room_id: SelectRoom.roomId,
                    status: 2,
                  });
                  if (data.code == 0) {
                    getroom();
                    setcontextMenu(false);
                  }
                }}
              >
                <div className="yuan doubleRoom"></div>
                <div className="RoomText AABB">
                  {intl.formatMessage({ id: 'business.Set Dirty' })}
                </div>
              </div>
            )}
            {/* {(SelectRoom.status == 1 || SelectRoom.status == 2) && (
              <>
                <p></p>
                <div style={{ width: 130, display: 'flex', alignItems: 'center' }}>
                  <div className="divImg">
                    <img style={{ width: 25, height: 25 }} src={Hoter} alt="" />
                  </div>
                  <div
                    className="AABB"
                    onClick={NocardTetrunRoom}
                    style={{ fontWeight: 550, fontSize: 15 }}
                  >
                    历史记录
                  </div>
                </div>
              </>
            )} */}
            <p></p>
            {SelectRoom.status == 3 && (
              <div
                style={{ width: 130, display: 'flex', alignItems: 'center' }}
                onClick={() => {
                  useDeleteConfirm(
                    `${SelectRoom.checkInPeople}${intl.formatMessage({ id: 'business.without' })}`,
                    '',
                    async (res) => {
                      if (res == true) {
                        let result = await NoCardcheckout(SelectRoom.roomId);
                        if (result.code == 0) {
                          message.success(
                            intl.formatMessage({ id: 'business.No card checkout successful' }),
                          );
                          getroom();
                          setcontextMenu(false);
                          api.open({
                            // message: `如果前卡丢失请将【${SelectRoom.roomName}】门锁挂失`,
                            message: intl.formatMessage(
                              { id: 'business.Card Loss' },
                              { SelectRoom: SelectRoom.roomName },
                            ),
                            icon: <InfoCircleOutlined style={{ color: 'red' }} />,
                            description: ' ',
                            duration: 6,
                            placement: 'topRight',
                          });
                        } else {
                          message.error(result.msg);
                        }
                      }
                    },
                  );
                }}
              >
                <div className="divImg">
                  <img src={svgImage} alt="" />
                </div>
                <div className="AABB" style={{ fontWeight: 550, fontSize: 15 }}>
                  无卡退房
                </div>
              </div>
            )}
          </div>
        )}
        {/* 房间渲染 按楼层   */}
        {isFloorVisible ? (
          <div className="digRoom">
            {list.map((item: RoomList, index: number) => {
              return (
                <React.Fragment key={index}>
                  <div className="RoomAll">
                    {intl.formatMessage({ id: 'business.The layer' }, { itemLayer: item.layer })}
                  </div>
                  {/* 0干净房 1脏房 2入住房 3维修房 */}
                  <div className="Roomitem">
                    {item.list.map((RoomItem: any, itemIndex: number) => {
                      return (
                        <div
                          key={RoomItem.id}
                          ref={refscaling}
                          onClick={() => showModal(RoomItem)}
                          onContextMenu={(event) => handleContextMenu(event, RoomItem)}
                          // draggable={RoomItem.status == "3" ? true : false}
                          // onDragStart={e => handleDragStart(e, RoomItem, itemIndex)}
                          // onDrop={e => handleDrop(e, RoomItem)}
                          // onDragOver={(e) => {
                          //   e.preventDefault();
                          //   setIsShowConter(true)
                          // }}
                          className={`ChildRoom ${
                            RoomItem.status == '1'
                              ? 'grey'
                              : RoomItem.status == '2'
                                ? 'doubleRoom'
                                : RoomItem.status == '3'
                                  ? 'blue'
                                  : RoomItem.status == '4'
                                    ? 'red'
                                    : 'yeelow'
                          }`}
                          style={{
                            width: scaling.w + 'vw',
                            height: scaling.h + 'vh',
                            fontSize: scaling.f,
                            minWidth: 135,
                            maxWidth: 300,
                            maxHeight: 135,
                            minHeight: 70,
                          }}
                        >
                          {RoomItem.roomName} <br />
                          <span>
                            {RoomItem.tName}
                            <br />

                            {RoomItem.status == '3' && (
                              <div>
                                <span style={{ color: '#fff' }}> {RoomItem.checkInPeople} </span>
                              </div>
                            )}
                          </span>
                          {!IsPhone && RoomItem.status == 3 && !contextMenu && (
                            <div className="hiddenInfo">
                              <div style={{ fontSize: '12px' }}>
                                {' '}
                                {intl.formatMessage({ id: 'business.Room number' })} :{' '}
                                {RoomItem.roomName}{' '}
                              </div>
                              <div style={{ fontSize: '12px' }}>
                                {intl.formatMessage({ id: 'business.Check-in time' })} :{' '}
                                {RoomItem.checkInStartTime}
                              </div>
                              <div style={{ fontSize: '12px' }}>
                                {intl.formatMessage({ id: 'business.Check-out time' })} :{' '}
                                {RoomItem.checkInEndTime}
                              </div>
                            </div>
                          )}
                          {RoomItem.isGroup == 1 && (
                            <div
                              style={{
                                color: 'crimson',
                                position: 'absolute',
                                right: '8px',
                                bottom: '8px',
                                fontWeight: '600',
                              }}
                            >
                              团
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </React.Fragment>
              );
            })}
          </div>
        ) : (
          // 不显示楼层
          <div className="digRoom" style={{ display: 'flex', flexWrap: 'wrap' }}>
            {list2.map((item: RoomList, itemIndex: number) => {
              return (
                <React.Fragment key={item.id}>
                  <div
                    key={item.id}
                    onClick={() => showModal(item)}
                    onContextMenu={(event) => handleContextMenu(event, item)}
                    // draggable={item.status == "3" ? true : false}
                    // onDragStart={e => handleDragStart(e, item, itemIndex)}
                    // onDrop={e => handleDrop(e, item)}
                    // onDragOver={(e) => {
                    //   e.preventDefault();

                    // }}
                    className={`ChildRoom ${
                      item.status == '1'
                        ? 'grey'
                        : item.status == '2'
                          ? 'doubleRoom'
                          : item.status == '3'
                            ? 'blue'
                            : item.status == '4'
                              ? 'red'
                              : 'yeelow'
                    }`}
                    style={{
                      width: scaling.w + 'vw',
                      height: scaling.h + 'vh',
                      fontSize: scaling.f,
                      minWidth: 135,
                      maxWidth: 300,
                      maxHeight: 135,
                      minHeight: 70,
                    }}
                  >
                    {item.roomName} <br />
                    <span>
                      {item.tName}
                      <br />
                      {item.status == '3' && (
                        <div>
                          <span style={{ color: '#fff' }}> {item.checkInPeople}</span>
                        </div>
                      )}
                    </span>
                    {!IsPhone && item.status == '3' && !contextMenu && (
                      <div className="hiddenInfo">
                        <div style={{ fontSize: '12px' }}>
                          {' '}
                          {intl.formatMessage({ id: 'business.Room number' })} :{' '}
                          {item.roomName}{' '}
                        </div>
                        <div style={{ fontSize: '12px' }}>
                          {intl.formatMessage({ id: 'business.Check-in time' })} :{' '}
                          {item.checkInStartTime}
                        </div>
                        <div style={{ fontSize: '12px' }}>
                          {intl.formatMessage({ id: 'business.Check-out time' })} :{' '}
                          {item.checkInEndTime}
                        </div>
                      </div>
                    )}
                    {item.isGroup == 1 && (
                      <div
                        style={{
                          color: 'crimson',
                          position: 'absolute',
                          right: '8px',
                          bottom: '8px',
                          fontWeight: '600',
                        }}
                      >
                        团
                      </div>
                    )}
                  </div>
                </React.Fragment>
              );
            })}
          </div>
        )}
      </Card>
      <div
        style={{
          fontSize: '14px',
          position: 'absolute',
          bottom: '-10px',
          right: '1%',
        }}
      >
        Copyright&copy;2025途明提供技术支持
      </div>
    </div>
  );
});

export default UserGroupList;
